//
//  LLGOAuthViewController.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/9.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

//AppKey
let WeiboAppKey = "842006997"

//AppSecret
let WeiboAppSecret = "9da7c840506741ef5118dee69162cea6"

//回调地址
let WeiboRedirect_Uri = "http://www.itcast.cn"

class LLGOAuthViewController: UIViewController {

    
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        
        //不透明度
        webView.opaque = false
        
        //设置代理
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
        //请求OAuth
        requestOAuthLogin()
        
    }
    
    // MARK: --设置导航栏
    private func setupNav() {
    
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFileAction")
    }
    
    // MARK: --点击事件
    @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFileAction() {
    
        print("自动填充")
    //自动填充
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18931857083';document.getElementById('passwd').value = '18931857083li'")
    }
    
    // MARK: --请求登录界面
    private func requestOAuthLogin() {
    
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"

        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        webView.loadRequest(request)
    }
    

}


// webView代理方法
extension LLGOAuthViewController: UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
        
            return false
        }
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        if let query = url.query where query.hasPrefix("code=") {
        
            let code = query.substringFromIndex("code=".endIndex)
            
            LLGUserAccountViewModel.sharedUserAccount.requestAccessToken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                
                    //切换控制器,dismiss该控制器
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //发送通知,切换根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(switchRootViewController, object: self)
                    })
                    
                    
                    print("登录成功")
                } else {
                    print("登录失败")
                }
                
            })

        } else {
        
            //取消授权,跳回主界面
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        SVProgressHUD.dismiss()
    }
    
}
